package com.minelx.datamicroscope.querylanguage.data;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class ColumnNames {

	private final Map<String, String> cachedResourceNames;

	private int currentIndex;

	private ColumnNames(int currentIndex) {
		this.currentIndex = currentIndex;

		cachedResourceNames = new HashMap<>();
	}

	public boolean checkExistence(String key) {
		return cachedResourceNames.containsKey(key);
	}

	public void selectItemSet(String key, String columnName) {
		cachedResourceNames.put(key, columnName);
	}

	public String obtainOnly(String key) {
		if (!cachedResourceNames.containsKey(key)) {
			throw new IllegalArgumentException("there is no cached column: " + key);
		}
		return cachedResourceNames.get(key);
	}

	public String joiningObtain(String key) {
		// check if there is a resource already cached
		if (cachedResourceNames.containsKey(key)) {
			return cachedResourceNames.get(key);
		}
		return joiningCreateNewColumn(key);
	}

	private String joiningCreateNewColumn(String key) {
		// move index forward
		++currentIndex;
		String result = "var" + currentIndex + "__for_" + key;
		// save to cache
		cachedResourceNames.put(key, result);
		return result;
	}

	public Collection<String> names() {
		return cachedResourceNames.values();
	}

	public static ColumnNames startsAt(int index) {
		return new ColumnNames(index);
	}

	public static ColumnNames empty() {
		return startsAt(0);
	}
}
